<template>
  <el-card class="container" style="width: 98%;margin: 20px;font-size: 14px;white-space: nowrap;">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基础信息" name="first">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="商品类型:" prop="type" class="label__label__font">
            <el-radio-group v-model="form.type">
              <el-radio :label="0" border >普通商品</el-radio>
<!--              <el-radio :label="2" border :disabled="isDisabled">卡密/网盘</el-radio>
              <el-radio :label="3" border :disabled="isDisabled">优惠券</el-radio>
              <el-radio :label="4" border :disabled="isDisabled">虚拟商品</el-radio>-->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品分类:" prop="categoryId" class="label__label__font">
            <el-cascader
              style="width: 400px"
              v-model="form.categoryId"
              :options="options"
              :props="{ multiple: true, checkStrictly: true }"
              clearable
              placeholder="请选择商品分类"
              ></el-cascader>
          </el-form-item>
          <el-form-item label="商品名称:" prop="goodsName" class="custom-width-form-item label__label__font">
            <el-input v-model="form.goodsName" placeholder="请输入商品名称" class="custom-width-input"/>
          </el-form-item>
          <el-form-item label="商品单位:" prop="goodsUnit" class="custom-width-form-item label__label__font">
            <el-input v-model="form.goodsUnit" placeholder="请输入商品单位" class="custom-width-input"/>
          </el-form-item>
          <el-form-item label="商品轮播图:" prop="goodsImg" class="label__label__font">
            <el-upload action="#" :auto-upload="false" list-type="picture-card" :limit="10" :on-change="handleUploadChange" :file-list="fileList" :on-remove="handleRemove" :disabled="disabledUpload">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file, fileList}">
              <img class="el-upload-list__item-thumbnail" :src="file.url || file.thumbUrl" alt="">
                <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
              </div>
            </el-upload>
            <div class="upload-tip" :style="uploadTipStyle">建议尺寸：800*800，最多上传10张。</div>
            <!--            <el-button @click="submitAllFiles">上传所有图片</el-button>-->
          </el-form-item>
          <el-form-item label="商品状态:">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.sys_goods_status"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="nextStep('second')">下一步</el-button>
          </el-form-item>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="规格库存" name="second">
        <el-form ref="form" :model="form" label-width="100px">
          <el-form-item label="商品规格:" prop="goodsAttr" class="label__label__font">
            <el-radio-group v-model="form.goodsAttr">
              <el-radio :label="'0'">单规格</el-radio>
<!--              <el-radio :label="'1'" :disabled="isDisabled">多规格</el-radio>-->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品图片:" prop="mainImgUrl" class="label__label__font">
            <el-upload
              class="avatar-uploader"
              :headers="uploadImg.headers"
              :action="uploadImg.url"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 110px;height: 110px;display: block;">
              <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;font-size: 28px;color: #8c939d;width: 110px;height: 110px;line-height: 110px;text-align: center;"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="售价:" prop="sellingPrice" class="label__label__font">
            <el-input-number
              v-model.number="form.sellingPrice"
              :precision="2"
              :step="0.1"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="成本价:" prop="costPrice" class="label__label__font">
            <el-input-number
              v-model.number="form.costPrice"
              :precision="2"
              :step="0.1"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="原价:" prop="price" class="label__label__font">
            <el-input-number
              v-model.number="form.price"
              :precision="2"
              :step="0.1"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="库存量:" prop="stock" class="label__label__font">
            <el-input-number
              v-model.number="form.stock"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="商品编号:" prop="goodsSn" class="custom-width-form-item label__label__font">
            <el-input v-model="form.goodsSn" placeholder="请输入商品编号" class="custom-width-input"/>
          </el-form-item>
          <el-form-item label="重量(KG):" prop="weight" class="label__label__font">
            <el-input-number
              v-model.number="form.weight"
              :precision="2"
              :step="0.1"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="体积(m³):" prop="volume" class="label__label__font">
            <el-input-number
              v-model.number="form.volume"
              :precision="2"
              :step="0.1"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="nextStep('first')">上一步</el-button>
            <el-button type="primary" @click="nextStep('third')">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="商品详情" name="third">
        <el-form ref="form" :model="form" label-width="100px">
          <el-form-item label="商品详情:" prop="goodsDetails" class="label__label__font">
            <div class="content_text" style="width: 1000px; height: 600px; overflow-y: auto;">
              <quill-editor v-model="form.goodsDetails" :options="editorOption"></quill-editor>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button @click="nextStep('second')">上一步</el-button>
            <el-button type="primary" @click="nextStep('fourth')">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="物流设置" name="fourth">
        <el-form ref="form" :model="form" :rules="ruleFourth" label-width="100px">
          <el-form-item label="物流方式:" prop="logisticsMode" class="label__label__font">
            <el-checkbox-group v-model="form.logisticsMode">
              <el-checkbox v-for="item in logisticsOptions" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button @click="nextStep('third')">上一步</el-button>
            <el-button type="primary" @click="nextStep('fifth')">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="营销设置" name="fifth">
        <el-form ref="form" :model="form" label-width="100px">
          <el-form-item label="已售数量:" prop="quantitySold" class="label__label__font">
            <el-input-number
              v-model.number="form.quantitySold"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="排序:" prop="orderNum" class="label__label__font">
            <el-input-number
              v-model.number="form.orderNum"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="单独设置:" prop="isExtension" class="label__label__font">
            <el-checkbox-group v-model="form.isExtension">
              <el-checkbox v-for="item in ExtensionOptions" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <div v-if="form.isExtension.length > 0">
            <el-table :data="this.form.setExtensionData" border style="width: 511px">
              <el-table-column label="一级佣金" align="center" width="255">
                <template slot-scope="scope">
                  <el-input-number
                    v-model.number="scope.row.firstLevelCommission"
                    :precision="2"
                    :step="0.1"
                    controls-position="right"
                    :min="0"
                  />
                </template>
              </el-table-column>
              <el-table-column label="二级佣金" align="center" width="255">
                <template slot-scope="scope">
                  <el-input-number
                    v-model.number="scope.row.secondLevelCommission"
                    :precision="2"
                    :step="0.1"
                    controls-position="right"
                    :min="0"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form-item label="商品推荐:" prop="goodsRecommend" class="label__label__font">
            <el-checkbox-group v-model="form.goodsRecommend">
              <el-checkbox v-for="item in recommendOptions" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button @click="nextStep('fourth')">上一步</el-button>
            <el-button type="primary" @click="nextStep('sixth')">下一步</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="其他设置" name="sixth">
        <el-form ref="form" :model="form" label-width="100px">
          <el-form-item label="商品简介:" prop="desc" class="label__label__font">
            <el-input type="textarea" v-model="form.desc" placeholder="请输入商品简介"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="nextStep('fifth')">上一步</el-button>
            <el-button type="primary" @click="submitForm()">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>
import { categoryTree } from '@/api/goods/category'
import { addGoods, addFileGoodsImgs, getGoods, updateGoods} from '@/api/goods/goods'
import { getToken } from '@/utils/auth'
import { quillEditor } from 'vue-quill-editor'

export default {
  name: "add",
  dicts: ['sys_goods_status'],
  components: {
    quillEditor
  },
  data() {
    return {
      divStyle: {
        display: "none",
      },

      //富文本配置
      editorOption: {
        theme: 'snow', // 或者 'bubble'
      },
      //上传轮播图控制参数
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [], // 用于存储上传组件中的文件列表
      selectedFiles: [],

      activeName: 'first',
      //分类搜索下拉数据
      options: [],
      // 表单参数
      form: {
        categoryId: [], // 用于存储选中的商品分类ID数组
        goodsType: 0,
        type:0,
        goodsAttr: '0',
        status: null,
        goodsImg: [], // 用于存储最终要提交的图片数组
        logisticsMode: [2],
        goodsRecommend:[],
        mainImgUrl:null,
        sellingPrice: 0.00,
        costPrice:0.00,
        price:0.00,
        stock:0,
        weight:0.00,
        volume:0.00,
        quantitySold:0,
        orderNum:0,
        desc:null,
        goodsId: null,
        goodsSn: null,
        goodsName: null,
        goodsUnit: null,
        goodsDetails: null,
        goodsViews: 0,
        numberVisitors: 0,
        numberOrdered: 0,
        numberFavorites: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isExtension:[],
        setExtensionData:[{
          firstLevelCommission: 0,  // 默认阶梯人数为1
          secondLevelCommission: 0,   // 默认拼团价格为0
        }]
      },
      // 上传图片参数
      uploadImg: {
        // 设置上传的请求头部
        headers: { 'access-token': getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin/SGoods/goodsUploadFile"
      },
      logisticsOptions: [
        { value: 1, label: '快递' },
        { value: 2, label: '到店核销' }
      ],
      recommendOptions: [
        { value: 1, label: '热卖单品' },
        { value: 2, label: '促销单品' },
        { value: 3, label: '精品推荐' },
        { value: 4, label: '首发新品' },
        { value: 5, label: '优品推荐' },
      ],
      ExtensionOptions: [
        { value: 1, label: '佣金设置(数字即返佣金额)' },
      ],
      imageUrl: '',
      isDisabled:true,
      disabledUpload:false,
      // 表单校验
      rules: {
        categoryId: [
          { required: true, message: "商品类型不能为空", trigger: "blur" }
        ],
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        goodsUnit: [
          { required: true, message: "商品单位不能为空", trigger: "blur" }
        ],
        goodsImg: [
          { required: true, message: "商品轮播图不能为空", trigger: "blur" }
        ],
      },
      ruleFourth:{
        logisticsMode: [
          { required: true, message: "物流方式不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.fetchCategoryTree();
    this.form.status = this.defaultStatus;
  },
  // 使用计算属性来处理逻辑
  computed: {
    defaultStatus() {
      const firstItem = this.dict?.type?.sys_goods_status?.[0];
      return firstItem?.value ?? '0';
    },
    uploadTipStyle() {
      if (this.fileList.length > 0) {
        return {
          'margin-top': '-20px',
        };
      }
      return {};
    },
  },
  methods: {
    nextStep(activeName) {
      this.activeName = activeName;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.mainImgUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    async fetchCategoryTree() {
      try {
        const response = await categoryTree();
        this.options = response.data;
        const goodsId = this.$route.params?.goodsId;
        if (goodsId && goodsId > 0) {
          await this.fetchGoodsDetails(goodsId);
        } else {
          this.fileList = [];
        }
      } catch (error) {
        console.error('Error fetching category tree or goods details:', error);
      }
    },
    async fetchGoodsDetails(goodsId) {
      try {
        const response = await getGoods(goodsId);
        this.form = response.data;
        this.form.type = 0;
        this.form.categoryId = this.form.categorySelected;
        this.imageUrl = `${process.env.VUE_APP_BASE_API}${this.form.mainImgUrl}`;
        this.fileList = this.form.goodsImg.map(item => ({
          url: `${process.env.VUE_APP_BASE_API}${item}`,
        }));
        if (this.fileList.length > 9) {
          this.disabledUpload = true;
        }
      } catch (error) {
        console.error('Error fetching goods details:', error);
      }
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },


    /********************开始**********************/
    async submitForm() {
      if (await this.validateForm()) {
        if (this.form.goodsId) {
          await this.updateGoods();
        } else {
          await this.addGoods();
        }
      }
    },

    async validateForm() {
      try {
        return await this.$refs.form.validate();
      } catch (error) {
        console.error('Form validation failed:', error);
        return false;
      }
    },

    async updateGoods() {
      this.form.goodsImg = [];
      const { selectedFiles, successUrls } = this.prepareFilesForUpdate();
      if (selectedFiles.length > 0) {
        const formData = new FormData();
        selectedFiles.forEach(file => {
          formData.append('images[]', file.raw);
        });

        await this.uploadImages(formData).then(uploadedImages => {
          this.form.goodsImg = uploadedImages;
        });

        await this.saveGoodsUpdates(successUrls);
      } else if (successUrls.length > 0) {
        await this.saveGoodsUpdates(successUrls);
      } else {
        this.$message.error('请上传商品轮播图!');
        return;
      }

      this.handleSuccessMessageAndRedirect('updateGoods');
    },

    async addGoods() {
      const { selectedFiles } = this.prepareFilesForAdd();

      if (selectedFiles.length === 0) {
        this.$message.error('请上传商品轮播图!');
        return;
      }

      if (this.form.goodsImg && this.form.goodsImg.length > 0) {
        // 如果已有图片数据，则直接添加商品
        await addGoods(this.form).then(response => {
          if (response.code === 200) {
            this.handleSuccessMessageAndRedirect('addGoods');
          }
        });
      } else {
        // 如果没有图片数据，则先上传图片
        const formData = new FormData();
        selectedFiles.forEach(file => {
          formData.append('images[]', file.raw);
        });

        await this.uploadImages(formData).then(uploadedImages => {
          this.form.goodsImg = uploadedImages;
          addGoods(this.form).then(response => {
            if (response.code === 200) {
              this.handleSuccessMessageAndRedirect('addGoods');
            }
          });
        });
      }
    },

    prepareFilesForUpdate() {
      let successUrls = [];
      this.selectedFiles = this.fileList.filter(item => {
        if (item.status === 'success') {
          const url = item.url;
          const prefix = process.env.VUE_APP_BASE_API;
          if (url.startsWith(prefix)) {
            successUrls.push(url.slice(prefix.length));
          } else {
            successUrls.push(url);
          }
          return false; // 移除这些已处理的文件
        }
        return true; // 保留其他文件
      });
      return { selectedFiles: this.selectedFiles, successUrls }; // 注意：这里应该是返回处理后的 selectedFiles，但上面逻辑有误，应直接返回 fileList 中 status 不为 'success' 的
    },

    prepareFilesForAdd() {
      return {
        selectedFiles: this.fileList
      };
    },

    async uploadImages(formData) {
      return await addFileGoodsImgs(formData).then(response => {
        if (response.code === 200) {
          return response.data;
        }
        throw new Error('Failed to upload images');
      });
    },

    async saveGoodsUpdates(oldImgUrls) {
      this.form.oldGoodsImg = oldImgUrls;
      return await updateGoods(this.form).then(response => {
        if (response.code === 200) {
          return true;
        }
        throw new Error('Failed to update goods');
      });
    },

    handleSuccessMessageAndRedirect(msg) {
      if(msg === 'addGoods'){
        this.$modal.msgSuccess("添加成功");
      }else{
        this.$modal.msgSuccess("修改成功");
      }
      setTimeout(() => {
        this.$router.push({ name: 'Goods', query: { refresh: true } });
      }, 2000);
    },
    /********************结束**********************/

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleUploadChange(file, fileList) {
      // 这里可以处理文件变化，比如添加文件到fileList
      this.fileList = fileList;
      if (this.fileList.length > 9) {
        this.disabledUpload = true;
      } else {
        this.disabledUpload = false;
      }
    },
    handleRemove(file) {
      // 从fileList中移除文件
      this.fileList = this.fileList.filter(f => f.uid !== file.uid);
      if (this.fileList.length > 9) {
        this.disabledUpload = true;
      } else {
        this.disabledUpload = false;
      }
    },
    submitAllFiles() {
      this.fileList = this.form.goodsImg.map(item => ({
        url: process.env.VUE_APP_BASE_API + item, // 假设 item 是图片的路径字符串
        // 如果需要，可以在这里添加其他属性，或者确保不添加不必要的属性
      }));
      console.log(this.fileList)
    },
  }
};
</script>

<style>
.el-upload--text{
  height: 110px;
}
.upload-tip {
  color: #999; /* 灰色文字 */
  font-size: 14px; /* 字体大小 */
  text-align: left; /* 文本居中 */
}
.el-upload-list--picture-card .el-upload-list__item {
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 85px;
  height: 85px;
  margin: 0 8px 8px 0;
  display: inline-block;
}

/* 或者只为特定 el-form-item 设置宽度 */
.custom-width-form-item {
  width: 500px;
}

/* 也可以直接为 el-input 设置宽度 */
.custom-width-input {
  width: 100%; /* 或者具体像素值 */
}

.quill-editor {
  height: 500px;
}
.el-textarea__inner {
  margin-top: 0px;
  margin-bottom: 0px;
  height: 100px;
  width: 400px;
}

.label__label__font label {
  font-size: 14px;
  font-weight: normal;
}
</style>
